var formidable = require('formidable');
var fs = require('fs');

var upload = {
	upvideo:function(req, path, callback){
		var form = new formidable.IncomingForm()
		var savePath = ''
		form.parse(req, function(err, fields, files){
			if (err) {

			} else {
				var oldPath = files.file.path
				fs.readFile(oldPath, function(err, fileData){
					if (err) {
						fs.unlinkSync(oldPath)
					} else {
						savePath = path+oldPath.replace(/\/tmp\/upload_/,'')+'.mp4'
						fs.writeFile(savePath, fileData, function(err){
							if (err) {
								fs.unlinkSync(oldPath)
							} else {
								fs.unlinkSync(oldPath)
								callback(oldPath.replace(/\/tmp\/upload_/,'')+'.mp4')
							}
						})
					}
				})
			}
		});

		form.on('progress', function(bytesReceived, bytesExpected){
			var data = parseInt(bytesReceived/bytesExpected*100)
			req.session.jin = data
		})
	}
}

module.exports = upload;